package com.api.apiopenplatclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.api.apiopenplatclientsdk.model.User;
import com.api.apiopenplatclientsdk.utils.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * description api调用
 *
 * @author tianzhou
 * @date 2023/3/22 17:06
 */
public class ApiClient {

    private final String accessKey;

    private final String secretKey;

    private final String gatewayIP;


    public ApiClient(String accessKey, String secretKey, String gatewayIP) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.gatewayIP = gatewayIP;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get("https://localhost:8123/api/name/getName", paramMap);
        System.out.println(result);
        return  result;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result = HttpUtil.post("https://localhost:8123/api/name/getNameByPost", paramMap);
        System.out.println(result);
        return  result;
    }

    Map<String,String> getRequestHeader(String body){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        hashMap.put("body",body);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", SignUtil.genSign(body, secretKey));
        return hashMap;
    }

    public String getNameByPostRest(User user) {
        String userJson = JSONUtil.toJsonStr(user);
        String url = gatewayIP + "/api/name/getNameByPostRest";
        HttpResponse httpResponse = HttpRequest.post(url)
                .addHeaders(getRequestHeader(userJson))
                .body(userJson)
                .execute();
        System.out.println(httpResponse.getStatus());
        return httpResponse.body();

    }


}

